<!--
 * @Author: error: git config user.name && git config user.email & please set dead value or install git
 * @Date: 2023-01-04 20:46:05
 * @LastEditors: 朱安武 549410045@qq.com
 * @LastEditTime: 2023-01-06 15:15:59
 * @FilePath: \vue-test\elementUi\src\components\BannerAdd.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-form label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="图片">
        <el-upload
          ref="upload"
          :limit="1"
          :auto-upload="false"
          list-type="picture"
          :on-change="onChangeImg"
          :on-exceed="onExceed"
          prop="img"
        >
          <template #trigger>
            <el-button type="primary">select file</el-button>
          </template>
        </el-upload>
      </el-form-item>
        <el-form-item label="图片文案" prop="alt">
          <el-input v-model="formData.alt" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="formData.link" />
        </el-form-item>
        <el-form-item>
          <el-button @click:handleSubmit="handleSubmit">提交</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { genFileId } from 'element-plus'
import { addBanner } from '../services/index' 
import { reactive,getCurrentInstance } from 'vue'

//定义可用事件
const props = defineProps(['dialogVisible'])
const emit = defineEmits(['add-succuss'])

//定义数据
const formData = reactive({
  formData:{
    img:'',
    alt: '',
    link: ''
  }
})

//定义规则
const rules = reactive({
        img: [
          { required: true, trigger: 'blur', message: '请选择图片' }
        ],
        alt: [
          { required: true, trigger: 'blur', message: '请填写文案' }
        ],
        link: [
          { required: true, trigger: 'blur', message: '请填写地址' }
        ],
})

//提交
const handleSubmit = ()=>{
  console.log('111');
  addBanner(formData.formData).then((result)=>{
    emit('add-success')
  })
}

//验证上传
const upload = getCurrentInstance()
const onExceed = files=>{
  upload.refs.upload.clearFiles()

  const file = files[0]
  file.uid = genFileId()

  upload.refs.upload.hanleStart(file)
}

//转换图片base 64 类型
const onChangeImg = file=>{
  const fileReader = new FileReader()
  fileReader.onload = ()=>{
    formData.formData.img = fileReader.result
  }
  fileReader.readAsDataURL(file.raw)
}
</script>